package com.i2863.shiroDemo.util;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author cexy
 * @date 2020/11/16 15:01
 * @description: 线程池配置
 */
public class ThreadPoolUtils {
    private ThreadPoolUtils() {
    }

    //阻塞队列。当核心线程都被占用，且阻塞队列已满的情况下，才会开启额外线程。
    private static final BlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(10);

    //线程工厂
    private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() {
        private final AtomicInteger integer = new AtomicInteger();

        @Override
        public Thread newThread(@NotNull Runnable r) {
            return new Thread(r, "myThreadPool thread:" + integer.getAndIncrement());
        }
    };

    //线程池
    private static final ThreadPoolExecutor THREAD_POOL;

    static {
        //线程池核心线程数
        int core = 5;
        //线程池最大线程数
        int max = 100;
        //额外线程空状态生存时间
        int time = 10000;
        THREAD_POOL = new ThreadPoolExecutor(core, max, time, TimeUnit.SECONDS, WORK_QUEUE, THREAD_FACTORY);
    }

    /**
     * 从线程池中抽取线程，执行指定的Runnable对象
     *
     * @param runnable
     */
    public static void execute(Runnable runnable) {
        THREAD_POOL.execute(runnable);
    }
}
